import 'package:chewie/chewie.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/news/video_controls.dart';
import 'package:flutter_syt/domain/waystation/map_helper.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:video_player/video_player.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../global_easy_loading.dart';

@RoutePage(name: "eyeDetail")
class GameSingleDetail extends StatefulWidget {
  final String id;

  GameSingleDetail(this.id);

  @override
  _GameSingleDetailState createState() => _GameSingleDetailState();
}

class _GameSingleDetailState extends State<GameSingleDetail> {
  //是否已结束
  bool isloading = true;
  GameDetailSingleData? data;
  ChewieController? _chewieController;
  VideoPlayerController? _playerController;
  int videoSelected = 0;
  bool needPlay = true;
  String? error;

  // LocationData? _locationData;
  // String? _distance;
  @override
  void dispose() {
    _playerController?.dispose();
    _chewieController?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _initInfo();

    ///定位测试
    // LocationHelper.instance.result((LocationData event) async {
    //   if (event.location?.latitude != null) {
    //     _locationData = event;
    //   }
    //   // LocationHelper.stopLocation();
    //   // calculationDistance();
    // });
    // LocationHelper.instance.startLocation();
    super.initState();
  }

  // calculationDistance() async {
  //   if (_locationData != null && data?.address.lat != 0) {
  //     // var distance = await BMFCalculateUtils.getLocationDistance(
  //     //         BMFCoordinate(_locationData?.location?.latitude ?? 0.0,
  //     //             _locationData?.location?.longitude ?? 0.0),
  //     //         BMFCoordinate(
  //     //             data?.address.lat ?? 0.0, data?.address.long ?? 0.0)) ??
  //     //     0;
  //     var distance = UtilsComment.getDistance(
  //         BMFCoordinate(_locationData?.location?.latitude ?? 0.0,
  //             _locationData?.location?.longitude ?? 0.0),
  //         BMFCoordinate(data?.address.lat ?? 0.0, data?.address.long ?? 0.0));
  //     if (mounted) {
  //       setState(() {
  //         _distance = (distance / 1000).toStringAsFixed(2);
  //       });
  //     }
  //   } else {
  //     _distance = null;
  //   }
  // }

  Widget loading() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

  Future _initVideo() async {
    if (data?.url != null) {
      try {
        _playerController?.pause();
        _playerController = VideoPlayerController.network(data?.url ?? "");
        await _playerController?.initialize();
        appContext.connectivitySubscription.onData((datas) async {
          appContext.connectionStatus = datas.first;
        });
        if (!needPlay) {
          return;
        }

        _chewieController = ChewieController(
          autoPlay: true,

          allowedScreenSleep: false,
          // fullScreenByDefault: true,
          // allowFullScreen: true,
          // deviceOrientationsOnEnterFullScreen: ,
          progressIndicatorDelay: Duration(milliseconds: 40),
          customControls: VideoCustomControls(null, true),
          aspectRatio: _playerController!.value.aspectRatio,
          deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
          // deviceOrientationsOnEnterFullScreen: [
          //   DeviceOrientation.landscapeLeft
          // ],
          videoPlayerController: _playerController!,
        );
        if (appContext.connectionStatus == ConnectivityResult.wifi) {
          // _chewieController = ChewieController(
          //   autoPlay: true,
          //   allowedScreenSleep: false,
          //   // deviceOrientationsOnEnterFullScreen: ,
          //   customControls: VideoCustomControls(null, true),
          //   deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
          //   videoPlayerController: _playerController!,
          // );
        } else {
          // _chewieController = ChewieController(
          //   autoPlay: false,
          //   allowedScreenSleep: false,
          //   customControls: VideoCustomControls(null, true),
          //   deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
          //   videoPlayerController: _playerController!,
          // );

          customShowToast(S.current.game_mobiledata);
        }
      } catch (e) {}
    }
    setState(() {});
  }

  Future _initInfo() async {
    setState(() {
      isloading = true;
    });
    try {
      try {
        data = await API.shared.game.eyeDetail(widget.id);
        // calculationDistance();
      } catch (e) {
        print('object');
      }
      if (!mounted) {
        return;
      }
      error = null;
      _initVideo();
    } on DioException catch (e) {
      if (e.type == DioExceptionType.unknown) {
        error = "无网络请重试";
      } else {
        error = e.message;
      }
    } catch (e) {
      error = "$e";
    }

    setState(() {
      isloading = false;
    });
  }

  Widget errorBody() {
    return Center(
      child: TextButton(
        child: ViewStateEmptyWidget(
          message: error,
        ),
        onPressed: ClickUtils.debounce(() {
          _initInfo();
        }),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget body;
    if (isloading) {
      body = loading();
    } else if (error != null) {
      body = errorBody();
    } else {
      var gameData = data;
      if (gameData == null) {
        body = Container();
      } else {
        body = Container(
          padding: EdgeInsets.fromLTRB(15, 20, 15, 0),
          child: ListView(
            children: [
              Container(
                child: Text(
                  gameData.title,
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w600,
                    color: Color(0xff000000),
                  ),
                ),
              ),
              Container(
                height: 14,
              ),
              gameVideo(),
              gameGround(),
            ],
          ),
        );
      }
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          S.of(context).Details_2,
        ),
      ),
      body: WillPopScope(
        onWillPop: () async {
          debugPrint("is pop ---------------  ");
          needPlay = false;
          _playerController?.pause();
          return true;
        },
        child: body,
      ),
    );
  }

  Widget gameVideo() {
    Widget video = Container();
    var real = '';
    try {
      real = data?.url ?? '';
    } catch (e) {}
    if (real == '') {
      return video;
    }
    if (data?.video_status == "0") {
      video = Container(
        padding: EdgeInsets.only(top: 20),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Container(
            color: Colors.black,
            child: Center(
              child: Flexible(
                child: Text(
                  data?.video_status_name ?? "",
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ),
      );
    } else if (_playerController != null && _chewieController != null) {
      video = Container(
        padding: EdgeInsets.only(top: 20),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          // aspectRatio: _playerController!.value.aspectRatio,
          child: Chewie(
            controller: _chewieController!,
          ),
        ),
      );
    } else if (real.length > 0) {
      video = Container(
        padding: EdgeInsets.only(top: 20),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: Container(
            color: Colors.black,
          ),
        ),
      );
    }
    return video;
  }

  Widget gameGround() {
    return Container(
      margin: EdgeInsets.only(top: 26.0),
      padding: EdgeInsets.fromLTRB(10, 12, 16, 12),
      decoration: BoxDecoration(
          border: Border.all(color: Color(0xffE4E4E4), width: 1),
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Color(0xffDEDEDE).withOpacity(0.5),
              blurRadius: 5.0,
              offset: Offset(3.0, 0),
            ),
          ],
          image: DecorationImage(
            image: AssetImage(
              'assets/images/game_map_bg.png',
            ),
            fit: BoxFit.cover,
          )),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            data?.address.name ?? '',
            softWrap: true,
            style: TextStyle(
              fontSize: 12,
              color: ThemeColor.colorBlack80,
            ),
          ),
          Text(
            // venue.address,
            data?.address.detail ?? '',
            softWrap: true,
            style: TextStyle(
              fontSize: 10,
              color: ThemeColor.colorBlack40,
            ),
          ),
        ],
      ),
      // child: Column(
      //   crossAxisAlignment: CrossAxisAlignment.start,
      //   mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      //   children: [
      //     GestureDetector(
      //       onTap: ClickUtils.debounce(() {
      //         // _playerController?.pause();
      //       }),
      //       child: Container(
      //         // margin: EdgeInsets.only(top: 12),
      //         padding: EdgeInsets.fromLTRB(10, 12, 16, 12),
      //         width: double.infinity,
      //         child: Row(
      //           crossAxisAlignment: CrossAxisAlignment.center,
      //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //           children: [
      //             Expanded(
      //               child: Row(
      //                 children: [
      //                   // Image.asset(
      //                   //   'assets/images/game_member.png',
      //                   //   width: 40,
      //                   //   height: 40,
      //                   // ),
      //                   // Container(
      //                   //   width: 10,
      //                   // ),
      //                   Expanded(
      //                     child: Column(
      //                       crossAxisAlignment: CrossAxisAlignment.start,
      //                       mainAxisAlignment: MainAxisAlignment.center,
      //                       children: [
      //                         Text(
      //                           data?.address.name ?? '',
      //                           softWrap: true,
      //                           style: TextStyle(
      //                             fontSize: 12,
      //                             color: ThemeColor.colorBlack80,
      //                           ),
      //                         ),
      //                         Text(
      //                           // venue.address,
      //                           data?.address.detail ?? '',
      //                           softWrap: true,
      //                           style: TextStyle(
      //                             fontSize: 10,
      //                             color: ThemeColor.colorBlack40,
      //                           ),
      //                         ),
      //                       ],
      //                     ),
      //                   ),
      //                 ],
      //               ),
      //             ),
      //             // GestureDetector(
      //             //     onTap: ClickUtils.debounce(() {
      //             //       MapNavigatorUtil.showBottom(context,
      //             //           latitude: (data?.address.lat ?? 0.0).toString(),
      //             //           longitude: (data?.address.long ?? 0.0).toString());
      //             //     }),
      //             //     behavior: HitTestBehavior.opaque,
      //             //     child: Column(
      //             //       mainAxisAlignment: MainAxisAlignment.center,
      //             //       children: [
      //             //         Image.asset(
      //             //           'assets/icons/location_icon.png',
      //             //           width: 18,
      //             //         ),
      //             //         Container(
      //             //           height: 5,
      //             //         ),
      //             //         Text(
      //             //           '${_distance ?? "-"}km',
      //             //           style: TextStyle(
      //             //             fontSize: 10,
      //             //             color: ThemeColor.colorBlack40,
      //             //           ),
      //             //         ),
      //             //       ],
      //             //     ))
      //           ],
      //         ),
      //       ),
      //     ),
      //   ],
      // ),
    );
  }
}

class GameDetailSingleData {
  late int video_status;
  late String video_status_name;
  late String cover;
  late String title;
  late String url;
  late GameDetailSingleAddressData address;
  GameDetailSingleData(Map<String, dynamic> json) {
    this.video_status_name = "${json["video_status_name"]}";
    this.cover = "${json["cover"]}";
    this.title = "${json["title"]}";
    this.url = "${json["url"]}";
    try {
      this.video_status = json["video_status"] as int;
    } catch (e) {
      this.video_status = 0;
    }
    this.address = GameDetailSingleAddressData(json["address"]);
  }
  Map<String, dynamic> get json {
    var result = Map<String, dynamic>();
    result["video_status_name"] = this.video_status_name;
    result["cover"] = this.cover;
    result["title"] = this.title;
    result["video_status"] = this.video_status;
    result["address"] = this.address.json;
    return result;
  }
}

class GameDetailSingleAddressData {
  late String name;
  late String detail;
  late double long;
  late double lat;
  GameDetailSingleAddressData(Map<String, dynamic> json) {
    this.name = "${json["name"]}";
    this.detail = "${json["detail"]}";
    try {
      this.long = double.parse("${json['long']}");
      lat = double.parse("${json['lat']}");
    } catch (e) {
      long = 0;
      lat = 0;
    }
  }
  Map<String, dynamic> get json {
    var result = Map<String, dynamic>();
    result["name"] = this.name;
    result["detail"] = this.detail;
    result["long"] = this.long;
    result["lat"] = this.lat;
    return result;
  }
}
